import requests
from bs4 import BeautifulSoup
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta

r = requests.get('http://sousuo.gov.cn/s.htm?t=govall&q=%E8%8A%82%E5%81%87%E6%97%A5')
# print(r.text)
soup = BeautifulSoup(r.text, 'html.parser')
holidays=[]
weekDays=[]
def fillDate(date,month):
    if len(date) >= 3:
        return parse(date).strftime('%Y-%m-%d')
    else: 
     return parse(month + '-' + date).strftime('%Y-%m-%d')

def fillDiffDate(dates):
    if len(dates) == 1:
        date = parse(dates[0]).strftime('%Y-%m-%d')
        return holidays.append(date)
    else:
        month = dates[0].split('-')[0]
        startDate = parse(fillDate(dates[0], month=month))
        endDate = parse(fillDate(dates[1],month=month))
        alter_day = relativedelta(days=+1)
        holidays.append(startDate.strftime('%Y-%m-%d'))
        while(startDate!=endDate):
            startDate = startDate + alter_day
            holidays.append(startDate.strftime('%Y-%m-%d'))

    


def parseHtml(link):
    # responseData = {'holidays':[],'work':[]}
    # print('link'+responseData)
    detailPage = requests.get(link)
    #解决中文乱码
    detailPage.encoding='utf-8'
    detailPageDom = BeautifulSoup(detailPage.text,'html.parser')
    pTags = detailPageDom.body.find_all('p')
    # print(pTags)
    for index in range(len(pTags)):
        # print()
        text = pTags[index].getText()
        
        # print(text)
        if len(text) != 0 and text.find('、') == 1:
            # print(text)
            # 解析节假日
            holidayText = text[text.find('：')+1:text.find('放假')].replace('年','-').replace('月','-').replace('日','')
            dateTmp = holidayText.split('至')
            fillDiffDate(dateTmp)
            #解析调休日
            weekDayText=text[text.find('。')+1:len(text)-1]
            # print(weekDayText)
            if weekDayText!='':
                weekDayArray=weekDayText.split('、')
                for index in range(len(weekDayArray)):
                    weekDate=parse(weekDayArray[index][0:weekDayArray[index].find('（')].replace('月','-').replace('日','')).strftime('%Y-%m-%d')
                    # print(weekDate)
                    weekDays.append(weekDate)

        # print(1)

h3 = soup.body.find_all('h3')
# print(soup.body.h3.a.contents[0])
for index in range(len(h3)):
#    print(h3[index].getText())
   if h3[index].getText().find('日历:2023年部分节假日安排') >-1:
       attrs = h3[index].a.attrs
    #    print(attrs.get('href'))
       parseHtml(attrs.get('href'))
       break
print('节假日')
print(holidays)
print('调休日')
print(weekDays)



# print(h3)
